package com.artron.mediaartron.ui.fragment.center;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.artron.baselib.adapter.recyclerview.BaseViewHolder;
import com.artron.baselib.adapter.recyclerview.CommonAdapter;
import com.artron.baselib.adapter.recyclerview.HeaderAndFooterWrapper;
import com.artron.baselib.adapter.recyclerview.LoadMoreWrapper;
import com.artron.baselib.base.BaseLoadingFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.DensityUitls;
import com.artron.baselib.utils.ToastUtil;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.MaterialData;
import com.artron.mediaartron.data.entity.MaterialData.MaterialListBean;
import com.artron.mediaartron.data.entity.MaterialWithDate;
import com.artron.mediaartron.data.entity.UploadMaterialData;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.net.NetConstant;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.task.MaterialLibraryTask;
import com.artron.mediaartron.ui.activity.PictureSelectionActivity;
import com.artron.mediaartron.ui.adapter.LoadMoreListener;
import com.artron.mediaartron.ui.fragment.dialog.ProgressDialogFragment;
import com.artron.mediaartron.ui.widget.GridFactoryView;
import com.artron.mediaartron.util.CacheUtils;
import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.List;
import java.util.ListIterator;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;

import static com.artron.mediaartron.ui.activity.PictureSelectionActivity.IS_HAVE_TAB_FRAGMENT;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-11-14.
 */

public class MaterialManagerFragment extends BaseLoadingFragment<MaterialData> implements View.OnClickListener {

    private static final String TAG = "MaterialManagerFragment";
    private static final int REQUEST_CODE = 6000;
    @BindView(R.id.MaterialManagerFragment_recycler)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.MaterialManagerFragment_refresh)
    protected SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.MaterialManagerFragment_tv_upload)
    protected TextView mTvUpload;
    @BindView(R.id.MaterialManagerFragment_tv_manager)
    protected TextView mTvManager;

    private ClassicsHeader mRefreshHeader;
    private List<MaterialWithDate> mFragmentData;
    private boolean isCheckVisible;
    private LoadMoreWrapper mWrapper;
    private ProgressDialogFragment mProgressDialogFragment;
    private MaterialLibraryTask mUpLoadTask;


    public static MaterialManagerFragment newInstance() {
        Bundle args = new Bundle();
        MaterialManagerFragment fragment = new MaterialManagerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_material_manager;
    }

    @Override
    protected void initVariable() {
        mRefreshHeader = new ClassicsHeader(mContext);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        show();
    }

    @Override
    public void initViewWithData(MaterialData data) {
        mFragmentData = data.getList();
        initRecycler(data);
        mTvManager.setOnClickListener(this);
        mTvUpload.setOnClickListener(this);

        initUpload();
    }

    private void initUpload() {
        mProgressDialogFragment = ProgressDialogFragment.newInstance("上传图片中，请稍等");
        mProgressDialogFragment.setOnBackPressListener(new Action0() {
            @Override
            public void call() {
                if (mUpLoadTask != null) {
                    mUpLoadTask.cancel();
                }
            }
        });
    }

    private void initRecycler(MaterialData data) {
        mRefreshLayout.finishRefresh();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false));
        CommonAdapter<MaterialWithDate> adapter = new CommonAdapter<MaterialWithDate>(mContext,
                R.layout.item_material_manager, mFragmentData) {

            @Override
            protected void onViewHolderCreate(final BaseViewHolder holder) {
                holder.setOnClickListener(R.id.ItemMaterialManager_tv_all, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = holder.getAdapterPosition();
                        MaterialWithDate bean = mFragmentData.get(position - 1);
                        boolean checkAll = !bean.isCheckAll();
                        bean.setCheckAll(checkAll);
                        for (MaterialListBean item : bean.getContentData()) {
                            item.setChecked(checkAll);
                        }
                        //这里获取的既是全部Item的正确位置
                        mWrapper.notifyItemChanged(position);
                    }
                });
            }

            @Override
            protected void convert(BaseViewHolder holder, final MaterialWithDate bean, final int position) {
                holder.setText(R.id.ItemMaterialManager_tv_date, bean.getUploadDate())
                        .setVisible(R.id.ItemMaterialManager_tv_all, bean.isShowAll())
                        .setText(R.id.ItemMaterialManager_tv_all, bean.isCheckAll() ? "取消" : "全选");

                GridFactoryView factory = holder.getView(R.id.ItemMaterialManager_gfv_content);
                int rowCount = bean.getContentData().size() % 3 == 0 ? bean.getContentData().size() / 3 :
                        bean.getContentData().size() / 3 + 1;
                Log.d(TAG, "convert: " + position + "\t bean:" + bean);
                factory.setRowCount(rowCount, true);
                factory.setAdapter(new CommonAdapter<MaterialListBean>(mContext,
                        R.layout.item_material_manager_content, bean.getContentData()) {

                    @Override
                    protected void convert(final BaseViewHolder holder, MaterialListBean item, final int position) {
                        holder.setImageUrl(R.id.ItemMaterialManagerContent_iv_image, item.getSmallThumbnailImagePath())
                                .setVisible(R.id.ItemMaterialManagerContent_cb_check, isCheckVisible)
                                .setChecked(R.id.ItemMaterialManagerContent_cb_check, item.isChecked());

                        holder.setOnCheckChangeListener(R.id.ItemMaterialManagerContent_cb_check,
                                new CompoundButton.OnCheckedChangeListener() {
                                    @Override
                                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                        mDatas.get(position).setChecked(isChecked);
                                    }
                                });
                    }
                });
            }
        };
        HeaderAndFooterWrapper headerAdapter = new HeaderAndFooterWrapper(adapter);
        headerAdapter.addHeaderView(initHeaderView(data));
        mWrapper = new LoadMoreWrapper(headerAdapter);
        mWrapper.setLoadMoreView(R.layout.layout_loading_more);
        mWrapper.setOnLoadMoreListener(new LoadMoreListener<MaterialData, MaterialWithDate>(mFragmentData, mWrapper,
                new Func1<Integer, Observable<Response<MaterialData>>>() {
                    @Override
                    public Observable<Response<MaterialData>> call(Integer integer) {
                        String passId = AppProfile.getUserInfo().getPassId();
                        return RetrofitHelper.getMaterialApi().queryMaterial(passId, integer, 50);
                    }
                }) {
            @Override
            protected List<MaterialWithDate> getDataList(MaterialData data) {
                data.setFragmentData(mFragmentData);
                isUpdateLastOne = true;
                return super.getDataList(data);
            }
        });
        mRecyclerView.setAdapter(mWrapper);


        mRefreshLayout.setRefreshHeader(mRefreshHeader);
        mRefreshLayout.setOnRefreshListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                showImmediate();
                mFragmentData = null;
            }
        });
    }

    private View initHeaderView(MaterialData data) {
        BaseViewHolder holder = BaseViewHolder.createViewHolder(mContext,
                null, R.layout.item_material_manager_header);
        View view = holder.getView(R.id.ItemMaterialManagerHeader_fl_all_size);
        int widthSpec = View.MeasureSpec.makeMeasureSpec(DensityUitls.dip2px(258), View.MeasureSpec.EXACTLY);
        int heightSpec = View.MeasureSpec.makeMeasureSpec(DensityUitls.dip2px(13), View.MeasureSpec.EXACTLY);
        view.measure(widthSpec, heightSpec);
        int allSizeWidth = view.getMeasuredWidth();
        long size = Long.parseLong(data.getUsedSpaceSize());
        String fileSize = CacheUtils.formatFileSize(size);

        double percent = ((double) size) / (5.f * 1024.f * 1024.f * 1024);
        int realWidth = (int) (allSizeWidth * percent);
        holder.setText(R.id.ItemMaterialManagerHeader_tv_size, String.format(
                "存储空间 %s/5G", fileSize));
        View viewContent = holder.getView(R.id.ItemMaterialManagerHeader_size);
        ViewGroup.LayoutParams params = viewContent.getLayoutParams();
        params.width = realWidth;
        viewContent.setLayoutParams(params);

        View container = holder.getContentView();
        ViewGroup.LayoutParams containerParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        container.setLayoutParams(containerParams);
        return container;
    }


    @Override
    protected Observable<Response<MaterialData>> retrofitData() {
        String passId = AppProfile.getUserInfo().getPassId();
        return RetrofitHelper.getMaterialApi().queryMaterial(passId, 1, 50);
    }

    @Override
    protected int getErrorViewId() {
        return R.layout.fragment_picture_net;
    }

    @Override
    protected int getEmptyViewId() {
        return R.layout.fragment_picture_net;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.MaterialManagerFragment_tv_upload:
                if (!isCheckVisible) {
                    BoxingConfig config = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG)
                            .needCamera(R.drawable.ic_selection_picture_camera)
                            .withMaxCount(10);
                    Boxing boxing = Boxing.of(config).withIntent(mContext, PictureSelectionActivity.class);
                    Intent intent = boxing.getIntent();
                    intent.putExtra(IS_HAVE_TAB_FRAGMENT, false);
                    boxing.start((Activity) mContext, REQUEST_CODE);
                } else {
                    StringBuilder sbIds = new StringBuilder();
                    for (MaterialWithDate item : mFragmentData) {
                        for (MaterialListBean bean : item.getContentData()) {
                            if (bean.isChecked()) {
                                sbIds.append(bean.getId())
                                        .append(",");
                            }
                        }
                    }
                    if (!TextUtils.isEmpty(sbIds)) {
                        String passId = AppProfile.getUserInfo().getPassId();
                        RetrofitHelper.subscript(RetrofitHelper.getMaterialApi().
                                        deleteMaterial(passId, sbIds.substring(0, sbIds.length() - 1)),
                                new Action1<Response>() {
                                    @Override
                                    public void call(Response response) {
                                        if ("1".equals(response.getStatus())) {
                                            for (MaterialWithDate next : mFragmentData) {
                                                for (ListIterator<MaterialListBean> beanIterator =
                                                     next.getContentData().listIterator(); beanIterator.hasNext(); ) {
                                                    MaterialListBean bean = beanIterator.next();
                                                    if (bean.isChecked()) {
                                                        beanIterator.remove();
                                                    }
                                                }
                                            }
                                            mWrapper.notifyDataSetChanged();
                                        }
                                        ToastUtil.show(response.getMessage());

                                    }
                                });

                    }
                }
                break;
            case R.id.MaterialManagerFragment_tv_manager:
                isCheckVisible = !isCheckVisible;
                for (MaterialWithDate bean : mFragmentData) {
                    bean.setShowAll(isCheckVisible);
                }
                if (isCheckVisible) {
                    ((TextView) v).setText("取消");
                    mTvUpload.setText("删除");
                } else {
                    ((TextView) v).setText("管理");
                    mTvUpload.setText("上传");
                }
                mWrapper.notifyDataSetChanged();
                break;
        }
    }

    public void uploadImage(final String contentImage) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                mUpLoadTask = new MaterialLibraryTask();
                mProgressDialogFragment.show(getChildFragmentManager(), mProgressDialogFragment.getOurTag());

                User user = AppProfile.getUserInfo().getUser();
                mUpLoadTask.uploadMaterial(user.getPassId(), NetConstant.CLIENT_CODE,
                        contentImage, new Action1<UploadMaterialData>() {
                            @Override
                            public void call(UploadMaterialData data) {
                                mProgressDialogFragment.dismiss();

                                showImmediate();
                            }
                        });
            }
        });
    }
}
